package cn.car91.activity;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import cn.car91.R;
import cn.car91.adapter.MyOfflineCityBeanAdapter;
import cn.car91.bean.OfflineMapCityBean;
import cn.car91.bean.OfflineMapCityBean.Flag;
import cn.car91.utils.CheckStatusUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.HerilyAlertDialog.Builder;
import cn.car91.view.MyListView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

public class OfflineMapActivity extends BaseActivity {
    private MKOfflineMap offlineMap;

    @ViewInject(R.id.offlinehotcities)
    MyListView hotcitiesView;
    MyOfflineCityBeanAdapter mhAdapter;
    @ViewInject(R.id.offlinecities)
    MyListView citiesView;
    MyOfflineCityBeanAdapter mAdapter;
    @ViewInject(R.id.curcity)
    MyListView curCityView;
    MyOfflineCityBeanAdapter mcAdapter;

    /**
     * 离线地图的数据
     */
    private List<OfflineMapCityBean> mcDatas = new ArrayList<OfflineMapCityBean>();
    private List<OfflineMapCityBean> mhDatas = new ArrayList<OfflineMapCityBean>();
    private List<OfflineMapCityBean> mDatas = new ArrayList<OfflineMapCityBean>();

    /**
     * 目前加入下载队列的城市
     */
    private List<Integer> mCityCodes = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_offlinemap);
        super.onCreate(savedInstanceState);

        /**
         * 初始化离线地图
         */
        initOfflineMap();
        /**
         * 初始化ListView数据
         */
        initData();
        /**
         * 初始化ListView
         */
        initListView();

        ((TextView) findViewById(R.id.header_text)).setText("离线地图");
    }

    private void initListView() {
        mAdapter = new MyOfflineCityBeanAdapter(this);
        mAdapter.setmDatas(mDatas);
        citiesView.setAdapter(mAdapter);

        mhAdapter = new MyOfflineCityBeanAdapter(this);
        mhAdapter.setmDatas(mhDatas);
        hotcitiesView.setAdapter(mhAdapter);

        mcAdapter = new MyOfflineCityBeanAdapter(this);
        mcAdapter.setmDatas(mcDatas);
        curCityView.setAdapter(mcAdapter);
    }

    @OnItemClick(R.id.curcity)
    public void onCurCityItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
        OfflineMapCityBean cityBean = mcDatas.get(arg2);
        int cityId = cityBean.getCityCode();
        if (mCityCodes.contains(cityId)) {
        	mCityCodes.remove(Integer.valueOf(cityId));
            offlineMap.pause(cityId);
            mcDatas.get(arg2).setFlag(Flag.NO_STATUS);
            mcAdapter.notifyDataSetChanged();
        } else {
            mCityCodes.add(cityId);
            offlineMap.start(cityId);
            mcDatas.get(arg2).setFlag(Flag.PAUSE);
            mcAdapter.notifyDataSetChanged();
        }
    }

    @OnItemClick(R.id.offlinehotcities)
    public void onCityItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
        OfflineMapCityBean cityBean = mhDatas.get(arg2);
        int cityId = cityBean.getCityCode();
        if (mCityCodes.contains(cityId)) {
        	mCityCodes.remove(Integer.valueOf(cityId));
            offlineMap.pause(cityId);
            mhDatas.get(arg2).setFlag(Flag.NO_STATUS);
            mhAdapter.notifyDataSetChanged();
        } else {
            mCityCodes.add(cityId);
            offlineMap.start(cityId);
            mhDatas.get(arg2).setFlag(Flag.PAUSE);
            mhAdapter.notifyDataSetChanged();
        }
    }

    @OnItemClick(R.id.offlinecities)
    public void onHotCityItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
        OfflineMapCityBean cityBean = mDatas.get(arg2);
        int cityId = cityBean.getCityCode();
        if (mCityCodes.contains(cityId)) {
        	mCityCodes.remove(Integer.valueOf(cityId));
            offlineMap.pause(cityId);
            mDatas.get(arg2).setFlag(Flag.NO_STATUS);
            mAdapter.notifyDataSetChanged();
        } else {
            mCityCodes.add(cityId);
            offlineMap.start(cityId);
            mDatas.get(arg2).setFlag(Flag.PAUSE);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化离线地图
     */
    private void initOfflineMap() {
    	if(!CheckStatusUtil.isWifiConnected(OfflineMapActivity.this)){
    		HerilyAlertDialog.Builder builer = new Builder(OfflineMapActivity.this);
            builer.setMessage("当前为非WIFI网络\n\r请注意下载离线地图流量消耗");
            builer.create().show();
    	}
    	
        offlineMap = new MKOfflineMap();
        // 设置监听  
        offlineMap.init(new MKOfflineMapListener() {
            @Override
            public void onGetOfflineMapState(int type, int state) {
                switch (type) {
                    case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                        // 离线地图下载更新事件类型
                        MKOLUpdateElement update = offlineMap.getUpdateInfo(state);
                        for (OfflineMapCityBean bean : mDatas) {
                            if (bean.getCityCode() == state) {
                                bean.setProgress(update.ratio);
                                bean.setFlag(Flag.DOWNLOADING);
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                        for (OfflineMapCityBean bean : mhDatas) {
                            if (bean.getCityCode() == state) {
                                bean.setProgress(update.ratio);
                                bean.setFlag(Flag.DOWNLOADING);
                                break;
                            }
                        }
                        mhAdapter.notifyDataSetChanged();
                        for (OfflineMapCityBean bean : mcDatas) {
                            if (bean.getCityCode() == state) {
                                bean.setProgress(update.ratio);
                                bean.setFlag(Flag.DOWNLOADING);
                                break;
                            }
                        }
                        mcAdapter.notifyDataSetChanged();
                        break;
                    case MKOfflineMap.TYPE_NEW_OFFLINE:
                        // 有新离线地图安装
                        for (OfflineMapCityBean bean : mDatas) {
                            if (bean.getCityCode() == state) {
                                bean.setFlag(Flag.UPDATE);
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                        for (OfflineMapCityBean bean : mhDatas) {
                            if (bean.getCityCode() == state) {
                                bean.setFlag(Flag.UPDATE);
                                break;
                            }
                        }
                        mhAdapter.notifyDataSetChanged();
                        for (OfflineMapCityBean bean : mcDatas) {
                            if (bean.getCityCode() == state) {
                                bean.setFlag(Flag.UPDATE);
                                break;
                            }
                        }
                        mcAdapter.notifyDataSetChanged();
                        break;
                    case MKOfflineMap.TYPE_VER_UPDATE:
                        // 版本更新提示
                        break;
                }

            }
        });
    }

    private void initData() {
        // 获得所有热门城市  
        ArrayList<MKOLSearchRecord> offlineHotCityList = offlineMap.getHotCityList();

        ArrayList<MKOLSearchRecord> offlineCityList = offlineMap.getOfflineCityList();
        // 手动添加了重庆  
        MKOLSearchRecord chong = new MKOLSearchRecord();
        chong.cityID = 132;
        chong.cityName = "重庆市";
        offlineHotCityList.add(6, chong);
        // 获得所有已经下载的城市列表  
        ArrayList<MKOLUpdateElement> allUpdateInfo = offlineMap
                .getAllUpdateInfo();
        // 设置所有数据的状态  
        for (MKOLSearchRecord record : offlineCityList) {
            OfflineMapCityBean cityBean = new OfflineMapCityBean();
            cityBean.setCityName(record.cityName);
            cityBean.setCityCode(record.cityID);
            cityBean.setChildcities(record.childCities);
            if (allUpdateInfo != null)//没有任何下载记录，返回null,为啥不返回空列表~~  
            {
                for (MKOLUpdateElement ele : allUpdateInfo) {
                    if (ele.cityID == record.cityID)
                        cityBean.setProgress(ele.ratio);
                }
            }
            mDatas.add(cityBean);
        }

        for (MKOLSearchRecord record : offlineHotCityList) {
            OfflineMapCityBean cityBean = new OfflineMapCityBean();
            cityBean.setCityName(record.cityName);
            cityBean.setCityCode(record.cityID);
            cityBean.setChildcities(record.childCities);
            if (allUpdateInfo != null)//没有任何下载记录，返回null,为啥不返回空列表~~  
            {
                for (MKOLUpdateElement ele : allUpdateInfo) {
                    if (ele.cityID == record.cityID)
                        cityBean.setProgress(ele.ratio);
                }
            }
            mhDatas.add(cityBean);
        }

        try {
            OfflineMapCityBean cityBean = new OfflineMapCityBean();
            BDLocation location = getCar91Application().getmLocationClient().getLastKnownLocation();
            cityBean.setCityName(location.getCity());
            cityBean.setCityCode(Integer.parseInt(location.getCityCode()));
            if (allUpdateInfo != null)//没有任何下载记录，返回null,为啥不返回空列表~~  
            {
                for (MKOLUpdateElement ele : allUpdateInfo) {
                    if (ele.cityID == cityBean.getCityCode())
                        cityBean.setProgress(ele.ratio);
                }
            }
            mcDatas.add(cityBean);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    
    @Override
    protected void onDestroy() {
        offlineMap.destroy();
        super.onDestroy();
    }
}
